<template>
  <div class="UploadImageMutil">
    <template v-if="type == 'default'">
      <a-upload list-type="picture-card" :file-list="fileList" multiple @preview="handlePreview"
        :customRequest="uploadImage" @change="handleChange" :before-upload="beforeUpload">
        <div>
          <a-icon type="plus" /> <br>
          上传
        </div>
      </a-upload>
      <div class="ant-upload-text" v-html="des">

      </div>

      <a-modal :dialog-style="{ top: '20px' }" :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </template>

    <a-upload-dragger v-else-if="type == 'drag'" ref="upload" :multiple="true" :file-list="fileList"
      :customRequest="uploadImage" @change="handleChange" :before-upload="beforeUpload">
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox" />
      </p>
      <p class="ant-upload-text">
        点击或拖入文件上传
      </p>
    </a-upload-dragger>

    <template v-else-if="type == 'button'">
      <a-upload :defaultFileList="fileList" :file-list="fileList" multiple @preview="handlePreview" :customRequest="uploadImage"
        :showUploadList="showUploadList" @change="handleChange" :before-upload="beforeUpload">
        <a-button type="primary" style="border-radius: 8px">上传附件</a-button>
      </a-upload>

      <a-modal :dialog-style="{ top: '20px' }" :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </template>
  </div>
</template>

<script>
import { uploadImage } from '@/api/api'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  name: 'UploadImageMutil',
  props: {
    des: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'default'
    },
    length: {
      type: Number,
      default: 1
    },
    showUploadList: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      previewVisible: false,
      imgurl: [],
      fileList: [],
      defaultFileList: [],

      previewImage: ''
    }
  },
  watch: {
    // url: {
    //   handler(e) {
    //     if (e) {

    //     }

    //     //   this.defaultFileList.push(e.split(',').map(e => {
    //     //     return {
    //     //       url: process.env.VUE_APP_UPLOADIMG_URL + e,
    //     //       uid: new Date().getTime(),
    //     //       name: new Date().getTime()
    //     //     };
    //     //   }));
    //     // }
    //   },
    //   deep: true,
    //   immediate: true
    // }

  },
  components: {

  },
  created () {

  },
  mounted () {
    console.log(this.url)
    if (this.url) {
      const fileList = this.url.split(',').map(e => {
        let url = ''
        if (/(http|https):\/\/([\w.]+\/?)\S*/.test(e)) {
          url = e
        } else {
          url = e
        }
        return {
          url,
          uid: String(new Date().getTime()),
          name: String(new Date().getTime()),
          status: 'done',
          response: '',
          // type: 'image/jpeg'
        }
      })
      if (fileList instanceof Array) {
        this.fileList = fileList
      }
    } else {
      this.fileList = []
    }
  },

  methods: {
    setFileList(list) {
      this.fileList = list.map(item => {
        return {
          url: item.url,
          uid: String(new Date().getTime()),
          name: item.name,
          status: 'done',
          response: '',
        }
      })
    },
    clear() {
      console.log('-----clear-----')
      this.fileList = []
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.imgUrl && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.imgUrl || file.preview
      this.previewVisible = true
    },
    handleChange (info) {
      // const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png'
      // if (!isJpgOrPng) {
      //   // this.$message.error('请上传正确的图片格式!');
      //   return false
      // }

      if (info.file.size > 1000 * 1024 * 1024) {
        return false
      }

      let fileList = [...info.fileList]
      if (fileList.length > this.length) {
        this.$message.error('最多上传' + this.length + '张')
        return
      }

      fileList = fileList.map(file => {
        if (file.response) {
          file.imgUrl = file.response
        }
        return file
      })

      this.fileList = fileList
      this.imgurl = fileList.filter(file => {
        return file.imgUrl
      }).map(e => {
        return e.imgUrl
      }).join(',')

      if (this.imgurl) this.$emit('getUrl', this.imgurl)
      console.log('this.fileList',this.fileList)
      this.$emit('change', this.fileList)
    },
    beforeUpload (file, fileList) {
      // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      // if (!isJpgOrPng) {
      //   this.$message.error('请上传正确的图片格式!')
      //   return false
      // }
      if (file.size > 1000 * 1024 * 1024) {
        this.$message.error('文件大小不能超过1000兆!')
        return false
      }
      return true
    },
    uploadImage (e) {
      const formData = new FormData()
      formData.append('file', e.file)
      uploadImage(formData).then(res => {
        e.onSuccess(res.imgUrl)
        // this.$emit('getUrl', res.url);
      }).catch(() => {
        e.onError()
      })
    }
  }
}
</script>

<style scoped>
  .UploadImageMutil .ant-upload-text {
    line-height: 1.2;
    margin-top: -12px;
  }
</style>
